package com.uestc.servlet.statistics;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.uestc.admin.FileAdmin;
import com.uestc.hbase.MTable;
import com.uestc.servlet.ServletBase;
import com.uestc.util.JsonUtil;
import com.uestc.util.Log;

@WebServlet("/admin/filestatistics")
public class FileStatistics extends HttpServlet implements ServletBase {
	private static final long serialVersionUID = 1L;

	public FileStatistics() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String param = getParameter(request, "adminOpt"); // 管理选项
		if ("piecharts".equals(param)) {
			long qiniu_count = 0;
			long ks_count = 0;
			long qiniu2_count = 0;
			Log.logger.info("收到查询文件总数的请求");
			MTable mTable = new MTable("file");
			try {
				qiniu_count = mTable.getRowCounterWithCondition("file", "info", "location", "Qiniu");
				ks_count = mTable.getRowCounterWithCondition("file", "info", "location", "Jinshan");
				qiniu2_count = mTable.getRowCounterWithCondition("file", "info", "location", "Qiniu2");
				Log.logger.info("七牛云总数为：" + qiniu_count);
				Log.logger.info("金山云总数为：" + ks_count);
				Log.logger.info("七牛云2总数为：" + qiniu2_count);
				List<Object> arrayList = new ArrayList<>();
				HashMap<String, Object> map = new HashMap<>();
				map.put("name", "金山云");
				map.put("data", ks_count);
				arrayList.add(map);
				map = new HashMap<>();
				map.put("name", "七牛云");
				map.put("data", qiniu_count);
				arrayList.add(map);
				map = new HashMap<>();
				map.put("name", "七牛云2");
				map.put("data", qiniu2_count);
				arrayList.add(map);
				// map = new HashMap<>();
				// map.put("parts", arrayList);
				String jsonString = JsonUtil.createJsonString(arrayList);
				Log.logger.info(jsonString);
				writeMessage(response, jsonString);
			} catch (Throwable e) {
				Log.logException(e);
				return;
			} finally {
				mTable.close();
			}
		}
		if ("sumUpCloudSpaces".equals(param)) {
			FileAdmin fileAdmin = new FileAdmin();
			try {
				String result = fileAdmin.sumUpSizes().toJsonString();
				writeMessage(response, result);
				Log.logger.info(result);
			} catch (IllegalArgumentException | IllegalAccessException e) {
				Log.logException(e);
			}
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
